package com.wbc.smartHome.web;


import com.github.pagehelper.PageInfo;
import com.wbc.smartHome.model.*;
import com.wbc.smartHome.model.Menu;
import com.wbc.smartHome.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.List;

@RestController
@RequestMapping(path = "/api/adminCtl")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @PostMapping(path = "/admin")
    public Result admins(@RequestBody SearchAdmin searchAdmin){
        PageInfo<Admin> admins = adminService.AdminList(searchAdmin);
        Result result  = new Result(200,"查询成功",admins);
        return result;
    }

    @GetMapping(path = "/menu")
    public Result menu(){
        List<Menu> menus = adminService.menus();
        Result result = new Result(200, "查询成功", menus);
        return result;
    }

    @RequestMapping(path = "/save", method = RequestMethod.POST)
    public Result save(@RequestBody Admin admin,@RequestHeader("adminToken") String adminToken){
        if (admin.getId()==null){
            adminService.saveAdmin(admin, adminToken);
        }
        else {
            adminService.updateAdmin(admin,adminToken);
        }

        Result result = new Result(200, "保存成功", null);
        return  result;
    }

    @GetMapping(path = "/delete")
    public Result delete(int id){
        adminService.deleteAdmin(id);
        Result result = new Result(200, "删除成功", null);
        return result;
    }

    @GetMapping(path = "/getAdminById")
    public Result getAdminById(int id){
        Admin admin = adminService.getAdminById(id);
        Integer[] menuIds = new Integer[admin.getMenus().size()];
        for (int i = 0;i<admin.getMenus().size();i++){
            Menu menu = admin.getMenus().get(i);
            menuIds[i] = menu.getId();
        }
        admin.setMenuIds(menuIds);
        Result result =new Result(200, "查询成功", admin);
        return result;
    }

    @GetMapping(path = "/getAdminByAccount")
    public Result getAdminByAccount(String account){
        Admin admin = adminService.getAdminByAccount(account);
        Result result = new Result(200, "查询成功", admin);
        return result;
    }


    @RequestMapping(path = "/updatePassword")
    public Result updatePassword(@RequestBody UpdatePasswordAdmin updatePasswordAdmin, @RequestHeader("adminToken") String adminToken){
        Result result;
        boolean flag = adminService.updatePassword(updatePasswordAdmin,adminToken);
        if (flag){
            result = new Result(200, "保存成功", null);
        }
        else {
            result = new Result(201, "现有密码输入错误", null);
        }


        return  result;
    }
}
